package com.seo.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Cookie工具类
 * @author Administrator
 * @version 2017.12.01 11:40
 */
public class CookieUtil {

	/**
	 * 返回值
	 * @param request  request
	 * @param key key
	 * @return 返回值
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static String getValue(HttpServletRequest request, String key) {
		try {
			Cookie[] cookies = request.getCookies();

			if (cookies != null && cookies.length > 0) {
				for (Cookie cookie : cookies) {
					if (cookie.getName().equals(key)) {

						return cookie.getValue();
					}
				}
			}
			return "";
		} catch (Exception e) {
			return "";
		}

	}

	/**
	 * 设置Cookie
	 * @param response response
	 * @param key key
	 * @param value value
	 * @param time time
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static void setCookie(HttpServletResponse response, String key, String value, int time) {
		Cookie cookie = new Cookie(key, value);
		cookie.setMaxAge(60 * 60 * 24 * time); // 设置为15天
		cookie.setPath("/");
		response.addCookie(cookie);
	}

	/**
	 * 设置Cookie
	 * @param response response
	 * @param key key
	 * @param value value
	 * @param time time
	 * @param path path
	 * @param domain domain
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static void setCookie(HttpServletResponse response, String key, String value, int time, String path, String domain) {
		Cookie cookie = new Cookie(key, value);
		cookie.setMaxAge(60 * 60 * 24 * time); // 设置为15天
		cookie.setPath(path);
		cookie.setDomain(domain);
		response.addCookie(cookie);
	}
}
